/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-11-01
 * Time: 20:09
 */
public class Solution7 {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                break;
            }
        }

        if(fast == null || fast.next == null) {
            return null;
        }
        fast = head;

        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
